package isr.cloudgate.dashboard.servlet;

import isr.google.gdata.GDataClient;
import isr.google.gdata.data.GoogleSendAs;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SendAsServlet
 */
public class SendAsServlet extends HttpServlet {

	private static final Logger logger = Logger.getLogger(SendAsServlet.class
		.getName());
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		logger.info("send as request (post)");

		GDataClient client = null;

		try {
			String userId = request.getParameter("user");
			if (userId == null) {
				logger.warning("no user parameter found in send as request");
				return;
			}

			client = ServletUtilities.getAppsClient(request);
			if (client == null) {
				logger.warning("no apps client");
				return;
			}

			List<GoogleSendAs> sendAsList = client.getSendAs(userId);

			request.setAttribute("userId", userId);
			request.setAttribute("sendaslist", sendAsList);

			logger.info(String.format("send as for user '%s': %s", userId,
				sendAsList));

		} catch (Exception e) {

			logger.warning(e.toString());
			request.setAttribute("userMessage", e.toString());

		}

		request.getRequestDispatcher(JspPage.sendas).forward(request, response);

	}

}
